<template>
  <div class="app-container">
    <div class="box">
      <div class="box ordersetting">
        <div class="calendar">
          <!-- 年份 月份 -->
          <div class="month">
            <div class="currentdate">
              <span class="choose-year">{{ currentYear }}年</span>
              <span class="choose-month">{{ currentMonth }}月</span>
              <span>每日考勤时间为:{{attendanceTime}}</span>
            </div>
            <div class="choose">
              <el-button
                @click="handleAttendanceTime"
                v-hasPermi="['system:holidaySettings:handleAttendanceTime']"
              >统一设置考勤时间</el-button>
              &nbsp;&nbsp;
              <span
                @click="goCurrentMonth(currentYear, currentMonth)"
                class="gotoday"
                >今天</span
              >
              <span @click="pickPre(currentYear, currentMonth)">❮</span>
              <span @click="pickNext(currentYear, currentMonth)">❯</span>
            </div>
            <div class="clearfix"></div>
          </div>

          <!-- 星期 -->
          <div class="caldate">
            <ul class="weekdays">
              <li>周一</li>
              <li>周二</li>
              <li>周三</li>
              <li>周四</li>
              <li>周五</li>
              <li>周六</li>
              <li>周日</li>
            </ul>
            <!-- 日期 -->
            <ul class="days">
              <!-- v-for循环 每一次循环用<li>标签创建一天 -->
              <li v-for="dayobject in days" :key="dayobject.index">
                <template>
                  <!-- 非当前月份 -->
                  <div
                    class="other-month"
                    v-if="dayobject.day.getMonth() + 1 != currentMonth"
                  >
                    {{ dayobject.day.getDate() }}
                  </div>
                  <!-- 当前月 -->
                  <div
                    class="everyday"
                    v-if="dayobject.day.getMonth() + 1 == currentMonth">
                    <span class="datenumber">{{
                      dayobject.day.getDate()
                    }}</span>
                    <template v-for="obj in leftobj">
                      <template v-if="obj.selectDate == currentDate(dayobject.day)">
                        <div class="usual" :key="obj.id">
                          <p v-if="obj.holidayName">节假日名称:{{ obj.holidayName }}</p>
                        </div>
                      </template>
                    </template>
                    <button
                      @click="handleHolidayName(dayobject.day)"
                      class="orderbtn"
                      v-hasPermi="['system:holidaySettings:handleHolidayName']"
                    >设置节假日</button>
                  </div>
                </template>
              </li>
            </ul>
          </div>
        </div>

        <!-- 添加或修改节假日对话框 -->
        <el-dialog :title="title" :visible.sync="openHoliday" width="600px" append-to-body>
            <el-form ref="holidayForm" :model="holidayForm" :rules="holidayRules" label-width="100px">
              <el-form-item label="节假日名称" prop="holidayName">
                <el-input v-model="holidayForm.holidayName" placeholder="请输入节假日名称" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitHolidayForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-dialog>
           <!-- 添加或修改考勤时间对话框 -->
          <el-dialog :title="title" :visible.sync="openAttendanceSetting" width="600px" append-to-body>
            <el-form ref="attendanceSettingForm" :model="attendanceSettingForm" :rules="attendanceRules" label-width="100px">
              <el-form-item label="考勤时长" prop="attendanceTime" >
                <el-input-number v-model="attendanceSettingForm.attendanceTime" :precision="1" :step="0.1" :min="0" :max="24" size="small"></el-input-number>
              </el-form-item>
              <el-form-item label="上午考勤时段" prop="morningTime" >
                <el-time-select
                  v-model="attendanceSettingForm.morningAttendanceStartTime"
                  placeholder="起始时间"
                  :picker-options="{
                    start: '08:00',
                    step: '00:15',
                    end: '18:30'
                  }">
                </el-time-select>
                <el-time-select
                  v-model="attendanceSettingForm.morningAttendanceEndTime"
                  placeholder="结束时间"
                  :picker-options="{
                    start: '08:00',
                    step: '00:15',
                    end: '18:30',
                    minTime: attendanceSettingForm.morningAttendanceStartTime
                  }">
                </el-time-select>

              </el-form-item>
              <el-form-item label="下午考勤时段" prop="afternoonTime" >
                <el-time-select
                  v-model="attendanceSettingForm.afternoonAttendanceStartTime"
                  placeholder="起始时间"
                  :picker-options="{
                    start: '08:00',
                    step: '00:15',
                    end: '18:30'
                  }">
                </el-time-select>
                <el-time-select
                  v-model="attendanceSettingForm.afternoonAttendanceEndTime"
                  placeholder="结束时间"
                  :picker-options="{
                    start: '08:00',
                    step: '00:15',
                    end: '18:30',
                    minTime: attendanceSettingForm.afternoonAttendanceStartTime
                  }">
                </el-time-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitAttendanceSettingForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-dialog>
      </div>
    </div>
  </div>
</template>

  <script>
    import { listSetting,saveHolidayName  } from '../../../api/system/holidaySettings';
    import {attendanceList, saveAttendanceTime} from '../../../api/system/generalConfiguration';

export default {
  name: "holidaySettings",
  data() {
    return {
      today: new Date(), //当前日期
      currentDay: 1,
      currentMonth: 1,
      LocalMonth: 1,
      currentYear: 1970,
      currentWeek: 1,
      days: [],
      openHoliday:false,
      openAttendanceSetting:false,
      title:'',
      tempDay:0,
      holidayForm:{
        holidayName:''
      },
      //考勤时间
      attendanceTime:'',
      //考勤时间段
      morningAttendanceStartTime:'',
      morningAttendanceEndTime:'',
      afternoonAttendanceStartTime:'',
      afternoonAttendanceEndTime:'',

      attendanceSettingForm:{
        attendanceTime:0.0,
        //考勤时间段
        morningAttendanceStartTime:'',
        morningAttendanceEndTime:'',
        afternoonAttendanceStartTime:'',
        afternoonAttendanceEndTime:'',
      },
      leftobj: [], //用于装载页面显示的月份已经进行预约设置的数据
       // 表单校验
      holidayRules: {
        holidayName: [
          { required: true, message: "节假日名称不能为空", trigger: "blur" }
        ]
      },
      attendanceRules:{
        attendanceTime: [
          { required: true, message: "当天考勤时间不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created: function () {
    //在vue初始化时调用
    this.initData(null);
  },
  methods: {
    getList(){
      //发送ajax请求
      listSetting(this.currentYear,this.currentMonth).then(res=>{
          this.leftobj = res.data;
      });
      attendanceList().then(res => {
          const item = res.data.find(value => value.type === "ATTENDANCE_TIME") || {};
          this.attendanceTime = item.typeValue;
          const item1 = res.data.find(value => value.type === "ATTENDANCE_MORNING_START_TIME") || {};
          this.morningAttendanceStartTime = item1.typeValue;
          const item2 = res.data.find(value => value.type === "ATTENDANCE_MORNING_END_TIME") || {};
          this.morningAttendanceEndTime = item2.typeValue;
          const item3 = res.data.find(value => value.type === "ATTENDANCE_AFTERNOON_START_TIME") || {};
          this.afternoonAttendanceStartTime = item3.typeValue;
          const item4 = res.data.find(value => value.type === "ATTENDANCE_AFTERNOON_END_TIME") || {};
          this.afternoonAttendanceEndTime = item4.typeValue;
      })
    },
    // 取消按钮
    cancel() {
      this.openHoliday = false;
      this.openAttendanceSetting = false;
      this.reset();
    },
    handleHolidayName(day){
      this.reset();
      this.tempDay = this.currentDate(day);
      const item = this.leftobj.find(value => value.selectDate === this.tempDay) || {};
      if(item){
        this.holidayForm.holidayName = item.holidayName;
      }
      this.openHoliday = true;
    },
    handleAttendanceTime(){
      this.openAttendanceSetting = true;
      this.attendanceSettingForm.attendanceTime = +this.attendanceTime;
      this.attendanceSettingForm.morningAttendanceStartTime = this.morningAttendanceStartTime;
      this.attendanceSettingForm.morningAttendanceEndTime = this.morningAttendanceEndTime;
      this.attendanceSettingForm.afternoonAttendanceStartTime = this.afternoonAttendanceStartTime;
      this.attendanceSettingForm.afternoonAttendanceEndTime = this.afternoonAttendanceEndTime;
    },
    //提交
    submitHolidayForm(){
      this.$refs["holidayForm"].validate(valid => {
        if (valid) {
          const holidayName = this.holidayForm.holidayName;
          const item = this.leftobj.find(value => value.selectDate === this.tempDay) || {};
          saveHolidayName({id:item.id,selectDate:this.tempDay,isHoliday:1,holidayName:holidayName}).then(res=>{
              if(res.code === 200){
                this.$message.success(res.msg);
                this.openHoliday = false;
                this.getList();
              }
          })
        }
      })
    },
    submitAttendanceSettingForm(){
      this.$refs["attendanceSettingForm"].validate(valid => {
        if (valid) {
          saveAttendanceTime(this.attendanceSettingForm).then(res=>{
              if(res.code === 200){
                this.$message.success(res.msg);
                this.openAttendanceSetting = false;
                this.getList();
              }
          })
        }
      })
    },
    reset(){
      this.tempDay = undefined,
      this.holidayForm = {
        holidayName:''
      },
      this.attendanceSettingForm = {attendanceTime:0}
    },
    //获取当前时间
    currentDate(day){
        return this.formatDate(day.getFullYear(),day.getMonth()+1,day.getDate())
    },

    //初始化当前页要展示的日期
    initData: function (cur) {
      var date;
      var index = 0; //控制显示预定的天数
      if (cur) {
        date = new Date(cur);
      } else {
        var now = new Date();
        var d = new Date(this.formatDate(now.getFullYear(), now.getMonth(), 1));
        d.setDate(35);
        date = new Date(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
      }
      this.currentDay = date.getDate();
      this.currentYear = date.getFullYear();
      this.currentMonth = date.getMonth() + 1 ;
      this.currentWeek = date.getDay(); // //本月第一天是周几（周日0 周六 6）
      var today = new Date();
      this.LocalMonth = today.getMonth() + 1;
      if (this.currentWeek == 0) {
        this.currentWeek = 7;
      }
      var str = this.formatDate(
        this.currentYear,
        this.currentMonth,
        this.currentDay
      );
      this.days.length = 0;
      // 今天是周日，放在第一行第7个位置，前面6个
      //初始化本周
      for (var i = this.currentWeek - 1; i >= 0; i--) {
        var d = new Date(str);
        d.setDate(d.getDate() - i);
        var dayobject = {};
        dayobject.day = d;
        var now = new Date();
        if (
          d.getDate() === now.getDate() &&
          d.getMonth() === now.getMonth() &&
          d.getFullYear() === now.getFullYear()
        ) {
          dayobject.index = index++; //从今天开始显示供预定的数量
        } else if (index != 0 && index < 3) dayobject.index = index++; //从今天开始3天内显示供预定的数量
        this.days.push(dayobject); //将日期放入data 中的days数组 供页面渲染使用
      }

      //其他周
      if (this.currentWeek == 7) this.currentWeek = 0;
      if (this.currentWeek == 6) this.currentWeek = -1;
      for (var i = 1; i <= 35 - this.currentWeek; i++) {
        var d = new Date(str);
        d.setDate(d.getDate() + i);
        var dayobject = {}; //dayobject   {day:date,index:2}
        dayobject.day = d;
        var now = new Date();
        if (
          d.getDate() === now.getDate() &&
          d.getMonth() === now.getMonth() &&
          d.getFullYear() === now.getFullYear()
        ) {
          dayobject.index = index++;
        } else if (index != 0 && index < 3) dayobject.index = index++;
        this.days.push(dayobject);
      }

      this.getList();
    },
    //切换到当前月份
    goCurrentMonth: function (year, month) {
      var d = new Date();
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
    },
    //向前一个月
    pickPre: function (year, month) {
      // setDate(0); 上月最后一天
      // setDate(-1); 上月倒数第二天
      // setDate(dx) 参数dx为 上月最后一天的前后dx天
      var d = new Date(this.formatDate(year, month, 1));
      d.setDate(0);
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
    },
    //向后一个月
    pickNext: function (year, month) {
      var d = new Date(this.formatDate(year, month, 1));
      d.setDate(35); ////获取指定天之后的日期
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
    },
    // 返回 类似 2016-01-02 格式的字符串
    formatDate: function (year, month, day) {
      var y = year;
      var m = month;
      if (m < 10) m = "0" + m;
      var d = day;
      if (d < 10) d = "0" + d;
      return y + "-" + m + "-" + d;
    },
  },
};
</script>
<style lang="css" scoped>
@import '../../../assets/styles/staticCalendar.css';
</style>
